package com.spider.web.url.https;

/**
* 
* @(#)ReqWebUtil.java    1.0 08/05/23
* Copyright 2008 HISUN
* 
*/
 
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

 
/**
* 其中的https是以君子之心看天下,全信
* @author hwj
* @version 1.0
* @since
* 
*/
public final class ReqWebUtil {
    private String url;
    private String postData;//提交的数据
    private String filePath;//页面保存地址
    
    public ReqWebUtil(String url,String postData,String filePath){
        this.url=url;
        this.postData=postData;
        this.filePath=filePath;
    }
    
    /**
    * post方式提交
    */    
    public void reqHttpsByPost()throws Exception{
        toReqHttps("POST");
    }
    
    /**
    * 以君子之心看天下,全信https
    */
    public void toReqHttps(String method)throws Exception{
        BufferedInputStream httpsBufIns=null;
        BufferedOutputStream fileBufOus=null;
        BufferedOutputStream hurlBufOus=null;
        try {
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, new TrustManager[]{new TrustAnyTrustManager()}, new java.security.SecureRandom());
           
            URL console = new URL(this.url);
            HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();
            conn.setSSLSocketFactory(sc.getSocketFactory());
            conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
            
            //这句在抓不到页面时很有用
            conn.setRequestProperty("User-Agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows XP)");
             conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
             conn.setRequestProperty("Accept","text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2");
             conn.setRequestProperty("Connection","keep-alive");
            
            conn.setDoInput(true);
            
            if(this.postData!=null&&!"".equals(this.postData)&&"POST".equals(method)){
                conn.setDoOutput(true);
                hurlBufOus=new BufferedOutputStream(conn.getOutputStream());
                hurlBufOus.write(this.postData.getBytes());//这里面已经将RequestMethod设置为POST.前面设置无效
                hurlBufOus.flush();
            }else{
                conn.setRequestMethod(method);
            }
            conn.connect();
            System.out.println("conn.getRequestMethod="+conn.getRequestMethod());
            System.out.println(conn.getResponseCode());
            System.out.println(conn.getResponseMessage());
            InputStream is=conn.getInputStream();
            System.out.println(inputStream2String(is));
            httpsBufIns=new BufferedInputStream(conn.getInputStream());
            fileBufOus=new BufferedOutputStream(new FileOutputStream(this.filePath));
            int read=0;
            byte[] byteBuf=new byte[9412];
            while((read=httpsBufIns.read(byteBuf))!=-1){
                fileBufOus.write(byteBuf, 0, read);
            }
            
            
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
             
        }catch (KeyManagementException e) {
            e.printStackTrace();
         } catch (MalformedURLException e) {
            e.printStackTrace();
         } catch (IOException e) {
            e.printStackTrace();
         }finally{
            try{
                if(httpsBufIns!=null)httpsBufIns.close();
                if(fileBufOus!=null)fileBufOus.close();
                if(hurlBufOus!=null)hurlBufOus.close();
            }catch(IOException ioe){
                ioe.printStackTrace();
             }
        }
        
    }
    
    /**
    * 主要供http请求用
    * 这个方法很粗糙
    * @param method 表单提交方法
    * @throws AppException
    */
    public void toRequest(String method)throws  Exception{
        try {
            URL url = new URL(this.url);
            HttpURLConnection httpsUrl=(HttpURLConnection)url.openConnection();
            System.out.println("httpUrl.getClass="+httpsUrl.getClass());
            httpsUrl.setDoOutput(true);
            httpsUrl.setRequestMethod(method);//POST||GET
//            httpUrl.setRequestProperty("Content-type","text/html");
//            httpUrl.setRequestProperty("Connection", "Keep-Alive");
            BufferedOutputStream hurlBufOus=null;
            
            if(this.postData!=null&&!"".equals(this.postData)){
                httpsUrl.setDoInput(true);
                hurlBufOus=new BufferedOutputStream(httpsUrl.getOutputStream());
                hurlBufOus.write(this.postData.getBytes());//这里面已经将RequestMethod设置为POST.前面设置无效
                hurlBufOus.flush();
            }
//            httpUrl.connect();
            System.out.println("httpUrl.getRequestMethod()="+httpsUrl.getRequestMethod());
            System.out.println("httpUrl.getURL()="+httpsUrl.getURL());
            BufferedInputStream hurlBufIns=new BufferedInputStream(httpsUrl.getInputStream());
            BufferedOutputStream fileBufOus=new BufferedOutputStream(new FileOutputStream(this.filePath));
            int read=0;
            byte[] byteBuf=new byte[9412];
            while((read=hurlBufIns.read(byteBuf))!=-1){
                fileBufOus.write(byteBuf, 0, read);
            }
            
            if(hurlBufOus!=null)hurlBufOus.close();
            if(hurlBufIns!=null)hurlBufIns.close();
            if(fileBufOus!=null)fileBufOus.close();
            httpsUrl.disconnect();
            
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        
    }
    
    //自定义私有类
    private static class TrustAnyTrustManager implements X509TrustManager {
        
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }
    
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }
    
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[]{};
        }
    }
    
    private static class TrustAnyHostnameVerifier implements HostnameVerifier {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    }

 

 
public static void main(String args[]){    
	String urlget="https://www.cn.alibaba-inc.com/welcome.nsf/pages/welcome";
	String postData="";String filePath="C://MSWebBrowser/";
	ReqWebUtil req=new ReqWebUtil(  urlget,  postData,  filePath);
	try {
		req.reqHttpsByPost();
		
	} catch (Exception e1) {
		// TODO Auto-generated catch block
		e1.printStackTrace();
	}
       /* try{
        	URL    url = new URL("https://www.cn.alibaba-inc.com/welcome.nsf/pages/welcome");     
             HttpsURLConnection httpsConn = (HttpsURLConnection)url.openConnection();         

               //取得该连接的输入流，以读取响应内容                

              InputStream ins = httpsConn.getInputStream();                

              BufferedReader breader = new BufferedReader(new InputStreamReader(ins));       

              String info = breader.readLine();            

              while (info != null) {           

                       System.out.println("------------------------------info:"+info);          

                        info = breader.readLine();                   

                      System.out.println("------------------------------info:"+info);              

              }            

         }catch(Exception e){

                System.out.println("------------------------------e:"+e);        

        }    */        
}
public static void ss(){
	String urlget="https://www.cn.alibaba-inc.com/welcome.nsf/pages/welcome";
	String postData="";String filePath="C://MSWebBrowser/ss.htm";
	ReqWebUtil req=new ReqWebUtil(  urlget,  postData,  filePath);
	try {
		req.reqHttpsByPost();
		
	} catch (Exception e1) {
		// TODO Auto-generated catch block
		e1.printStackTrace();
	}
}
public static String inputStream2String(InputStream is) throws IOException {
	if (is == null) {
		return null;
	}
	BufferedReader in = new BufferedReader(new InputStreamReader(is));
	StringBuffer buffer = new StringBuffer();
	String line = "";
	while ((line = in.readLine()) != null) {
		buffer.append(line);
	}
	return buffer.toString();
}
}


